/**
 * Created by user on 2018/4/25.
 */
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { Router, Route, IndexRedirect } from 'react-router';
import history from '../history'
import App from '../app';
import Page from '../components/Page';
import Login from '../pages/login'
import NotFound from '../pages/NoMatchPage'
import DashBoard from '../pages/dashBoard'
import Weibo from '../pages/weibo'
import WeChat from '../pages/wechat'
import Tuniu from '../pages/tuniu'
import RecordPage from '../pages/record'

class CRouter extends Component {
  requireAuth(nextState, replace) {
    const { pathname: nextPath } = nextState.location
    const { auth } = this.props
    if (!auth) {
      replace({ pathname: '/login', state: {from: nextPath} })
    }
  }
  render() {
    return (
      <Router history={history}>
        <Route path={'/'} component={Page}>
          <IndexRedirect to="/app/dashboard/index"/>
          <Route path={'app'} component={App} onEnter={this.requireAuth.bind(this)}>
            <Route path={'dashboard'}>
              <Route path={'index'} component={DashBoard} />
            </Route>
            <Route path={'weibo'}>
              <Route path={'index'} component={Weibo} />
            </Route>
            <Route path={'weixin'}>
              <Route path={'index'} component={WeChat} />
            </Route>
            <Route path={'tuniu'}>
              <Route path={'index'} component={Tuniu} />
            </Route>
            <Route path={'record'}>
              <Route path={'index'} component={RecordPage} />
            </Route>
          </Route>
          <Route path={'login'} component={Login}/>
          <Route path={'404'} component={NotFound} />
        </Route>
      </Router>
    )
  }
}

const mapState = (state) => {
  const { auth } = state.LoginState
  return { auth }
}

export default connect(mapState)(CRouter)
